package com.gitee.wsl.ext.map


/**
 * Safely iterates over a map, catching exceptions for each entry.
 *
 * This function iterates over the entries of the map, executing the [block] for each entry.
 * If an exception is thrown during the execution of the block,
 * the [onException] handler is called with the entry and the exception.
 *
 * @param K The type of keys in the map.
 * @param V The type of values in the map.
 * @param onException A function that handles exceptions thrown during the execution of the block.
 * It receives the entry and the exception as parameters.
 * @param block The function to be executed for each entry.
 */
inline fun <K, V> Map<K, V>.forEachSafe(
    onException: (Exception, Map.Entry<K, V>) -> Unit = { _, _ -> },
    block: (Map.Entry<K, V>) -> Unit,
) {
    forEach {
        try {
            block(it)
        } catch (e: Exception) {
            onException(e, it)
        }
    }
}

